package top.hzy520.admin.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import top.hzy520.admin.user.dao.UserMapper;
import top.hzy520.admin.user.entity.User;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 19:27 2018/7/29
 */
public class MyshiroRealm extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;
    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
         User user= (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        user.getRoleList().stream().forEach(role -> {
            authorizationInfo.addRole(role.getRole());
            role.getPermissionList().stream().forEach(permission -> {
                authorizationInfo.addStringPermission(permission.getPermission());
            });
        });
        return authorizationInfo;
    }
     // 认证登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
             UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) authenticationToken;
              String username=usernamePasswordToken.getUsername();
            User user= userMapper.selectByUserName(username);
            if (user!=null){
                if (user.roleList.size()==0){
                    return null;
                }else {
                    SecurityUtils.getSubject().getSession().setAttribute("user",user);
                    return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
                }
            }
        return null;
    }
}
